import React, { useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import styles from './index.module.css'
import Nabar from '../../conpoment/Nabar'

// 开单项目接口
interface OrderItem {
  id: number;
  name: string;
  type: 'medicine' | 'check' | 'test';
  price: number;
  quantity?: number;
  unit: string;
  tags?: string[];
}

// 开单数据接口
interface OrderData {
  id: number;
  items: OrderItem[];
  hospital: string;
  applicationTime: string;
  amount: number;
  status: 'pending' | 'approved' | 'rejected' | 'cancelled';
  patientName?: string;
  patientId?: string;
  applicationReason?: string;
}

interface PaymentItem {
  id: string
  registrationNo: string
  department: string
  doctor: string
  orderTime: string
  amount: number
  selected: boolean
  // 新增开单数据相关字段
  orderData?: OrderData
  items?: OrderItem[]
}
const Index: React.FC = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const [activeTab, setActiveTab] = useState<'pending' | 'paid'>('pending')
  const [patientName, setPatientName] = useState('王小柯')
  const [patientId, setPatientId] = useState('2015****10')
  const [showPatientModal, setShowPatientModal] = useState(false)
  const [showOrderDetails, setShowOrderDetails] = useState(false)
  const [selectedOrderDetails, setSelectedOrderDetails] = useState<OrderData | null>(null)
  // 患者列表数据
  const [patients] = useState([
    { id: '1', name: '王小柯', patientId: '2015****10' },
    { id: '2', name: '李小明', patientId: '2016****25' },
    { id: '3', name: '张小红', patientId: '2017****38' }
  ])
  const [pendingItems, setPendingItems] = useState<PaymentItem[]>([])
  const [paidItems, setPaidItems] = useState<PaymentItem[]>([])

  // 处理从开单记录页面传递的数据
  useEffect(() => {
    const state = location.state as any;
    if (state && state.order) {
      // 从开单记录页面传递的订单数据
      const orderData: OrderData = state.order;
      const paymentItem: PaymentItem = {
        id: orderData.id.toString(),
        registrationNo: `ORD${orderData.id}`,
        department: '门诊开单',
        doctor: '系统开单',
        orderTime: orderData.applicationTime,
        amount: orderData.amount,
        selected: true,
        orderData: orderData,
        items: orderData.items
      };
      
      setPendingItems([paymentItem]);
      setPatientName(orderData.patientName || '王小柯');
      setPatientId(orderData.patientId || '2015****10');
    } else {
      // 默认数据
      setPendingItems([
        {
          id: '1',
          registrationNo: Date.now().toString(),
          department: '门诊外一科',
          doctor: '刘医师',
          orderTime: '2020-01-01 10:20:36',
          amount: 520.13,
          selected: true
        },
        {
          id: '2',
          registrationNo: Date.now().toString(),
          department: '口腔科',
          doctor: '章医师',
          orderTime: '2020-01-01 13:20:36',
          amount: 120.50,
          selected: false
        }
      ]);
    }
  }, [location.state]);
  const currentItems = activeTab === 'pending' ? pendingItems : paidItems
  const handleItemSelect = (id: string) => {
    if (activeTab === 'pending') {
      setPendingItems(items =>
        items.map(item =>
          item.id === id ? { ...item, selected: !item.selected } : item
        )
      )
    }
    // 已缴费项目不支持选择
  }
  const handleSelectAll = () => {
    if (activeTab === 'pending') {
      const allSelected = pendingItems.every(item => item.selected)
      setPendingItems(items =>
        items.map(item => ({ ...item, selected: !allSelected }))
      )
    }
  }
  const selectedItems = activeTab === 'pending'
    ? pendingItems.filter(item => item.selected)
    : []
  const totalAmount = selectedItems.reduce((sum, item) => sum + item.amount, 0)
  const selectedCount = selectedItems.length

  const handlePatientSwitch = (patient: { id: string; name: string; patientId: string }) => {
    setPatientName(patient.name)
    setPatientId(patient.patientId)
    setShowPatientModal(false)
  }
  const handleDetailsClick = (item: PaymentItem) => {
    if (activeTab === 'paid') {
      // 已缴费项目点击跳转到pingz页面
      navigate('/pingz')
    } else {
      // 待缴费项目显示缴费明细
      if (item.orderData) {
        setSelectedOrderDetails(item.orderData);
        setShowOrderDetails(true);
      } else {
        console.log('查看缴费明细:', item)
      }
    }
  }
  const handlePayClick = () => {
    if (selectedCount > 0) {
      // 跳转到pay页面，传递支付金额和选中的项目
      const selectedItemsData = selectedItems.map(item => ({
        id: item.id,
        registrationNo: item.registrationNo,
        department: item.department,
        doctor: item.doctor,
        orderTime: item.orderTime,
        amount: item.amount
      }))
      navigate(`/pay?amount=${totalAmount.toFixed(2)}&items=${encodeURIComponent(JSON.stringify(selectedItemsData))}`)
    }
  }


  // 监听localStorage变化，处理支付完成后的数据更新
  useEffect(() => {
    const handleStorageChange = () => {
      const paymentInfo = localStorage.getItem('paymentInfo')
      if (paymentInfo) {
        try {
          const paymentData = JSON.parse(paymentInfo)
          console.log('检测到支付完成:', paymentData)
          
          // 将支付的项目添加到已缴费列表
          const newPaidItems = paymentData.items.map((item: any) => ({
            ...item,
            id: `paid_${Date.now()}_${item.id}`, // 生成新的ID
            selected: false
          }))
          
          setPaidItems(prevItems => [...prevItems, ...newPaidItems])
          
          // 从待缴费列表中移除已支付的项目
          const paidItemIds = paymentData.items.map((item: any) => item.id)
          setPendingItems(prevItems => prevItems.filter(item => !paidItemIds.includes(item.id)))
          
          // 切换到已缴费标签页
          setActiveTab('paid')
          
          // 清除localStorage中的支付信息
          localStorage.removeItem('paymentInfo')
          
          alert('支付成功！项目已添加到已缴费列表')
        } catch (error) {
          console.error('解析支付信息失败:', error)
        }
      }
    }

    // 监听storage事件
    window.addEventListener('storage', handleStorageChange)
    
    // 页面加载时也检查一次
    handleStorageChange()

    return () => {
      window.removeEventListener('storage', handleStorageChange)
    }
  }, [])
  return (
    <div className={styles.container}>
     <Nabar title='门诊缴费' sticky={false} />
      {/* Patient Info */}
      <div className={styles.patientInfo}>
        <div className={styles.patientLeft}>
          <span className={styles.patientName}>{patientName}</span>
          <span className={styles.patientId}>{patientId}</span>
        </div>
        <div className={styles.patientRight} onClick={() => setShowPatientModal(true)}>
          <span className={styles.switchIcon}>👤⇄</span>
          <span className={styles.switchText}>切换</span>
        </div>
      </div>
      {/* Tabs */}
      <div className={styles.tabs}>
        <div
          className={`${styles.tab} ${activeTab === 'pending' ? styles.activeTab : ''}`}
          onClick={() => setActiveTab('pending')}
        >
          待缴费
        </div>
        <div
          className={`${styles.tab} ${activeTab === 'paid' ? styles.activeTab : ''}`}
          onClick={() => setActiveTab('paid')}
        >
          已缴费
        </div>
      </div>
      {/* Payment Items */}
      <div className={styles.paymentList}>
        {currentItems.map((item) => (
          <div key={item.id} className={styles.paymentItem}>
            <div className={styles.itemLeft}>
              <div className={styles.blueBar}></div>
            </div>
            <div className={styles.itemContent}>
              <div className={styles.registrationNo}>登记号: {item.registrationNo}</div>
              <div className={styles.department}>就诊科室: {item.department}</div>
              <div className={styles.doctor}>开单医生: {item.doctor}</div>
              <div className={styles.orderTime}>开单时间: {item.orderTime}</div>
              <div className={styles.amount}>
                {activeTab === 'pending' ? '开单金额' : '缴费金额'}: ¥{item.amount.toFixed(2)}
              </div>
              <div
                className={styles.detailsLink}
                onClick={() => handleDetailsClick(item)}
              >
                {activeTab === 'pending' ? '缴费明细' : '缴费凭证'} &gt;
              </div>
            </div>
            {activeTab === 'pending' && (
              <div className={styles.itemRight}>
                <div
                  className={`${styles.checkbox} ${item.selected ? styles.checked : ''}`}
                  onClick={() => handleItemSelect(item.id)}
                >
                  {item.selected && <span className={styles.checkmark}>✓</span>}
                </div>
              </div>
            )}
            {activeTab === 'paid' && (
              <div className={styles.itemRight}>
                <div className={styles.paidStatus}>已缴费</div>
              </div>
            )}
          </div>
        ))}
      </div>
      {/* Footer */}
      {activeTab === 'pending' && (
        <div className={styles.footer}>
          <div className={styles.footerLeft}>
            <div
              className={`${styles.selectAllCheckbox} ${pendingItems.every(item => item.selected) ? styles.checked : ''}`}
              onClick={handleSelectAll}
            >
              {pendingItems.every(item => item.selected) && <span className={styles.checkmark}>✓</span>}
            </div>
            <div>
              <div className={styles.selectAllText}>
                全选 (已选 {selectedCount} 张)
              </div>
              <div className={styles.totalAmount}>
                合计: ¥{totalAmount.toFixed(2)}
              </div>
            </div>
          </div>
          <div className={styles.footerRight}>
            <button className={styles.payButton} onClick={handlePayClick}>去缴费</button>
          </div>
        </div>
      )}
      {activeTab === 'paid' && (
        <div className={styles.footer}>
          <div className={styles.footerLeft}>
            <div className={styles.paidInfo}>
              共 {paidItems.length} 条缴费记录
            </div>
          </div>
        </div>
      )}
      {/* 患者切换弹框 */}
      {showPatientModal && (
        <div className={styles.modalOverlay} onClick={() => setShowPatientModal(false)}>
          <div className={styles.modalContent} onClick={(e) => e.stopPropagation()}>
            <div className={styles.modalHeader}>
              <span className={styles.modalTitle}>选择患者</span>
              <span className={styles.closeButton} onClick={() => setShowPatientModal(false)}>×</span>
            </div>
            <div className={styles.patientList}>
              {patients.map((patient) => (
                <div
                  key={patient.id}
                  className={`${styles.patientItem} ${patientName === patient.name ? styles.currentPatient : ''}`}
                  onClick={() => handlePatientSwitch(patient)}
                >
                  <div className={styles.patientInfo}>
                    <div className={styles.patientName}>{patient.name}</div>
                    <div className={styles.patientId}>{patient.patientId}</div>
                  </div>
                  {patientName === patient.name && (
                    <div className={styles.currentIndicator}>当前</div>
                  )}
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
      {/* 开单详情弹框 */}
      {showOrderDetails && selectedOrderDetails && (
        <div className={styles.modalOverlay} onClick={() => setShowOrderDetails(false)}>
          <div className={styles.modalContent} onClick={(e) => e.stopPropagation()}>
            <div className={styles.modalHeader}>
              <span className={styles.modalTitle}>开单详情</span>
              <span className={styles.closeButton} onClick={() => setShowOrderDetails(false)}>×</span>
            </div>
            <div className={styles.orderDetails}>
              <div className={styles.orderInfo}>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>申请医院:</span>
                  <span className={styles.infoValue}>{selectedOrderDetails.hospital}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>申请时间:</span>
                  <span className={styles.infoValue}>{selectedOrderDetails.applicationTime}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>申请原因:</span>
                  <span className={styles.infoValue}>{selectedOrderDetails.applicationReason || '无'}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>开单金额:</span>
                  <span className={styles.infoValue}>¥{selectedOrderDetails.amount.toFixed(2)}</span>
                </div>
              </div>
              <div className={styles.itemsSection}>
                <div className={styles.sectionTitle}>开单项目</div>
                <div className={styles.itemsList}>
                  {selectedOrderDetails.items.map((item) => (
                    <div key={item.id} className={styles.itemCard}>
                      <div className={styles.itemHeader}>
                        <div className={styles.itemTypeTag}>
                          {item.type === 'medicine' ? '药' : item.type === 'check' ? '检' : '验'}
                        </div>
                        <div className={styles.itemName}>{item.name}</div>
                        <div className={styles.itemPrice}>¥{item.price.toFixed(2)}</div>
                      </div>
                      <div className={styles.itemDetails}>
                        <div className={styles.itemQuantity}>
                          数量: {item.quantity || 1}{item.unit}
                        </div>
                        {item.tags && item.tags.length > 0 && (
                          <div className={styles.itemTags}>
                            {item.tags.map((tag, tagIndex) => (
                              <span key={tagIndex} className={styles.tag}>
                                {tag}
                              </span>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default Index
